<template>
  <div>
    <!-- 搜速区 -->
    <div class="search">
      <label style="color: #666; font-size: 12px">客户姓名：</label>
      <el-input
        size="mini"
        v-model="guestName"
        placeholder="请输入姓名"
        clearable
        style="width: 120px; margin-right: 10px"
      ></el-input>
      <label style="color: #666; font-size: 12px">结账状态：</label>
      <el-select
        size="mini"
        v-model="resideStateId"
        placeholder="请选择状态"
        clearable
        style="margin-right: 10px; width: 120px"
      >
        <el-option
          v-for="item in resideStateList"
          :key="item.resideStateId"
          :label="item.resideStateName"
          :value="item.resideStateId"
        >
        </el-option>
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="searchClick"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-document-add"
        size="small"
        @click="addClick"
      ></el-button>
      <el-button
        type="success"
        icon="el-icon-share"
        size="small"
        @click="excelClick"
      ></el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 99.9%" size="mini">
      <el-table-column label="客户姓名" width="80">
        <template slot-scope="scope">
          {{ scope.row.guestName }}
        </template>
      </el-table-column>
      <el-table-column label="客户电话" width="100">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="省份证号" width="150">
        <template slot-scope="scope">
          {{ scope.row.identityId }}
        </template>
      </el-table-column>
      <el-table-column label="房间类型" width="80">
        <template slot-scope="scope">
          {{ scope.row.room.roomType.roomTypeName }}
        </template>
      </el-table-column>
      <el-table-column label="房间号" width="80">
        <template slot-scope="scope">
          {{ scope.row.roomId }}
        </template>
      </el-table-column>
      <el-table-column label="床位数" width="60">
        <template slot-scope="scope">
          {{ scope.row.room.roomType.bedNum }}
        </template>
      </el-table-column>
      <el-table-column label="价格" width="60">
        <template slot-scope="scope">
          {{ scope.row.room.roomType.roomTypePrice }}
        </template>
      </el-table-column>
      <el-table-column label="人数" width="60">
        <template slot-scope="scope">
          {{ scope.row.guestNum }}
        </template>
      </el-table-column>
      <el-table-column label="入住日期" width="140">
        <template slot-scope="scope">
          {{ scope.row.resideDate }}
        </template>
      </el-table-column>
      <el-table-column label="离开日期" width="140">
        <template slot-scope="scope">
          {{ scope.row.leaveDate }}
        </template>
      </el-table-column>
      <el-table-column label="押金" width="80">
        <template slot-scope="scope">
          {{ scope.row.deposit }}
        </template>
      </el-table-column>
      <el-table-column label="消费金额" width="80">
        <template slot-scope="scope">
          {{ scope.row.totalMoney }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-tag
            size="small"
            :type="scope.row.resideStateId === 1 ? 'danger' : 'success'"
            disable-transitions
            >{{ scope.row.resideState.resideStateName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span></span>
          <el-button
            v-if="scope.row.resideStateId === 1"
            size="mini"
            type="text"
            style="color: #409eff"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.resideStateId === 1"
            size="mini"
            type="text"
            style="color: #e6a23c"
            @click="handleCheckOut(scope.$index, scope.row)"
            >结账</el-button
          >
          <el-button
            v-if="scope.row.resideStateId === 2"
            size="mini"
            type="text"
            style="color: #f56c6c"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="flex j-c" style="margin-top: 10px">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="count"
        :page-size="12"
        hide-on-single-page
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加抽屉 -->
    <el-drawer
      :title="isAdd ? '添加客户' : '修改客户'"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="drawerClose"
      size="30%"
      :wrapperClosable="false"
    >
      <div style="padding: 0 15px">
        <el-form
          size="mini"
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="75px"
          class="demo-ruleForm"
        >
          <el-form-item label="姓名" prop="guestName">
            <el-input
              type="text"
              v-model="ruleForm.guestName"
              autocomplete="off"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input
              type="text"
              v-model="ruleForm.phone"
              autocomplete="off"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="identityId">
            <el-input
              type="text"
              v-model="ruleForm.identityId"
              autocomplete="off"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="客房类型" prop="roomTypeId">
            <el-select
              size="mini"
              v-model="ruleForm.roomTypeId"
              placeholder="请选择类型"
              clearable
              @change="roomTypeChange"
              style="margin-right: 10px; width: 130px"
            >
              <el-option
                v-for="item in roomTypeList"
                :key="item.roomTypeId"
                :label="item.roomTypeName"
                :value="item.roomTypeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间号" prop="roomId">
            <el-select
              size="mini"
              v-model="ruleForm.roomId"
              placeholder="请选择状客房号"
              clearable
              style="margin-right: 10px; width: 130px"
            >
              <el-option
                v-for="item in roomList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入住时间" prop="resideDate">
            <el-date-picker
              v-model="ruleForm.resideDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择入住时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="离开时间" prop="resideDate">
            <el-date-picker
              v-model="ruleForm.leaveDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择入住时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="入住人数" prop="guestNum">
            <el-input
              type="text"
              v-model="ruleForm.guestNum"
              autocomplete="off"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="押金" prop="deposit">
            <el-input
              type="text"
              v-model="ruleForm.deposit"
              autocomplete="off"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              isAdd ? "添加" : "修改"
            }}</el-button>
            <el-button @click="resetForm('ruleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
// 导入xlsx方法
import { xlsx } from "../../util/xlsx";
export default {
  data() {
    // 验证
    var validateGuestName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择客房姓名"));
      } else {
        callback();
      }
    };
    var validateGuestNum = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入入住人数"));
      } else {
        callback();
      }
    };
    var validateIdentityId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入省份证号"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入电话"));
      } else {
        callback();
      }
    };
    var validateResideDate = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择入住日期"));
      } else {
        callback();
      }
    };
    var validateRoomTypeId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择客房类型"));
      } else {
        callback();
      }
    };
    var validateRoomId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入客房号"));
      } else {
        callback();
      }
    };
    var validateDeposit = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入押金"));
      } else {
        callback();
      }
    };
    return {
      // 表格数据
      tableData: [],
      // 表格数据的总数量
      count: 0,
      // 当前页
      pageIndex: 1,
      // 客户姓名(用于搜索)
      guestName: "",
      // 结账状态编号(用于搜索)
      resideStateId: "",
      // 结账状态列表(用于搜索)
      resideStateList: [],
      // 客房类型列表
      roomTypeList: [],
      // 房间列表
      roomList: [],
      // 是否做添加操作
      isAdd: true,
      // 是否打开抽屉
      drawer: false,
      //表单数据
      ruleForm: {
        // 客户编号
        guestId: "",
        // 客户姓名
        guestName: "",
        // 入住人数
        guestNum: "",
        // 省份证
        identityId: "",
        // 电话
        phone: "",
        // 入住日期
        resideDate: "",
        // 入住日期
        leaveDate: "",
        // 房间类型编号
        roomTypeId: "",
        // 房间号
        roomId: "",
        // 用于修改已使用的房间为空闲状态
        oldRoomId: "",
        // 押金
        deposit: "",
      },
      // 表单验证数据
      rules: {
        // 验证
        guestName: [{ validator: validateGuestName, trigger: "blur" }],
        guestNum: [{ validator: validateGuestNum, trigger: "blur" }],
        identityId: [{ validator: validateIdentityId, trigger: "blur" }],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        resideDate: [{ validator: validateResideDate, trigger: "blur" }],
        roomTypeId: [{ validator: validateRoomTypeId, trigger: "submit" }],
        roomId: [{ validator: validateRoomId, trigger: "submit" }],
        deposit: [{ validator: validateDeposit, trigger: "blur" }],
      },
    };
  },
  created() {
    // 调用获取表格数据的方法
    this.getTableData();
    // 获取获取结账状态列表的方法
    this.getResideStateList();
    // 调用获取客房类型列表的方法
    this.getRoomTypeList();
  },
  methods: {
    // 获取表格数据
    async getTableData() {
      // 获取房间类型信息
      let res = await this.$get("/guest/list", {
        guestName: this.guestName,
        resideStateId: this.resideStateId || 0,
        pageIndex: this.pageIndex,
        pageSize: 12,
      });
      this.tableData = res.data.list;
      // 设置总数量
      this.count = res.data.total;
    },
    // 获取结账状态列表的方法
    async getResideStateList() {
      let res = await this.$get("/guest/resideStateList");
      this.resideStateList = res.data;
    },
    // 获取客房类型列表
    async getRoomTypeList() {
      let res = await this.$get("/roomType/list");
      this.roomTypeList = res.data;
      this.roomTypeSearchList = res.data;
    },
    // 表示客房类型列表改变时的事件(需要改变相应的房间号)
    async roomTypeChange() {
      if (this.ruleForm.roomTypeId == "") {
        this.roomList = [];
      }
      // 先清空表单中roomId的值
      this.ruleForm.roomId = "";
      // 获取客房类型编号
      let roomTypeId = this.ruleForm.roomTypeId;
      if (roomTypeId) {
        // 根据客房类型编号获取房间号(客房状态必须是空闲的)
        let { data } = await this.$get("/guest/roomIdList", {
          roomTypeId,
          roomStateId: 1,
          guestId: this.ruleForm.guestId || 0,
        });
        this.roomList = data;
      }
    },
    // 分页方法
    currentChange(pageIndex) {
      // 设置当前页码
      this.pageIndex = pageIndex;
      // 重新调用获取表格数据的方法
      this.getTableData();
    },
    async handleEdit(index, row) {
      // 获取客户编号
      let guestId = row.guestId;
      // 根据房间编号获取对象
      let res = await this.$get("/guest/getOne", { guestId });
      // 表单中包含全部信息(可用于修改传值)
      this.ruleForm = res.data;
      this.ruleForm.roomTypeId = res.data.room.roomTypeId;
      // 保存一下roomId
      let saveRoomId = this.ruleForm.roomId;
      // 调用获取客房号的方法
      this.roomTypeChange();
      this.ruleForm.roomId = saveRoomId;
      // 获取原房间的房间号
      this.ruleForm.oldRoomId = saveRoomId;
      // 表示这是修改操作
      this.isAdd = false;
      // 打开抽屉
      this.drawer = true;
    },
    async handleDelete(index, row) {
      await this.$con_f("是否确定删除?");
      let guestId = row.guestId;
      // 删除对应的角色信息
      let { success, message } = await this.$post("/guest/delete", {
        guestId,
      });
      if (success) {
        this.$message({
          showClose: true,
          message: message,
          type: "success",
          duration: 1500,
        });
        // 获取最新数据
        this.getTableData();
      } else {
        this.$message({
          showClose: true,
          message: message,
          type: "error",
          duration: 1500,
        });
      }
    },
    async handleCheckOut(index, row) {
      await this.$con_f("是否确认结账?");
      // 获取编号
      let guestId = row.guestId;
      let { success, message, data } = await this.$post("/guest/checkout", {
        guestId,
      });
      if (success) {
        this.$message({
          showClose: true,
          message: message + "需支付" + data + "元",
          type: "success",
          duration: 1500,
        });
        // 获取最新数据
        this.getTableData();
      }
    },
    // 添加按钮点击方法
    addClick() {
      this.drawer = true;
    },
    searchClick() {
      this.getTableData();
    },
    // 导出Excel表的方法
    excelClick() {
      // 组织导出的数据
      let json = this.tableData.map((r) => {
        return {
          guestName: r.guestName,
          phone: r.phone,
          identityId: r.identityId,
          roomTypeName: r.room.roomType.roomTypeName,
          roomId: r.roomId,
          bedNum: r.room.roomType.bedNum,
          price: r.room.roomType.roomTypePrice,
          guestNum: r.guestNum,
          resideDate: r.resideDate,
          leaveDate: r.leaveDate,
          deposit: r.deposit,
          totalMoney: r.totalMoney,
          resideStateName: r.resideState.resideStateName,
        };
      });
      // 组织表头对象
      let fields = {
        guestName: "客户姓名",
        phone: "客户电话",
        identityId: "省份证号",
        roomTypeName: "房间类型",
        roomId: "房间号",
        bedNum: "床位数",
        price: "房间价格",
        guestNum: "入住人数",
        resideDate: "入住日期",
        leaveDate: "离开日期",
        deposit: "押金",
        totalMoney: "消费金额",
        resideStateName: "结账状态",
      };
      // 定义文件名称
      let fileName = "客户信息表";
      xlsx(json, fields, fileName);
    },
    // 关闭抽屉
    drawerClose(done) {
      // 清空表单数据
      this.resetForm("ruleForm");
      // 表单恢复成默认状态
      this.isAdd = true;
      done();
    },
    // 表单提交方法
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        // 判断表单数据是否验证成功
        if (valid) {
          if (this.isAdd) {
            console.log(this.ruleForm.resideDate);
            // 执行添加功能
            let { success, message } = await this.$post(
              "/guest/add",
              this.ruleForm
            );
            // 判断是否添加成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              // 清空表单
              this.resetForm("ruleForm");
              // 关闭抽屉
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          } else {
            // 执行修改操作
            let { success, message } = await this.$post(
              "/guest/update",
              this.ruleForm
            );
            // 判断是否修改成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 清空数据
      this.ruleForm = {
        // 客户姓名
        guestName: "",
        // 入住人数
        guestNum: "",
        // 省份证
        identityId: "",
        // 电话
        phone: "",
        // 入住日期
        resideDate: "",
        // 房间类型编号
        roomTypeId: "",
        // 房间号
        roomId: "",
        // 押金
        deposit: "",
      };
    },
  },
};
</script>
<style scoped lang='scss'>
.search {
  padding: 4px 10px;
}
</style>